import React, { Component } from 'react'
import Addstu from '../../components/Addstu'
import Showstu from '../../components/Showstu'
import Updatestu from '../../components/Updatestu'
import Searchstu from '../../components/Searchstu'

export default class Root extends Component {
    addStu = (stuObj) => {
        let {stuArr} = this.state;
        let newStuArr = [...stuArr,stuObj]
        this.setState({stuArr:newStuArr,stus:newStuArr});
    }
    updateStu = (stuObj) => {
        let {stuArr} = this.state;
        let newStuArr = stuArr.map(item => {
            if(item.name !== stuObj.name){
                return item
            }else{
                return stuObj
            }
        })
        this.setState({stuArr:newStuArr,stus:newStuArr});
    }
    updateInfo = (name,gender,age) => {
        this.stuInfo = {name,gender,age};
        this.setState({})  //让react调用一次render，使传递给更新组件的stuInfo有值
    }
    searchStu = (type,searchContent) => {
        let {stus} = this.state;
        if(type === 'name'){
            this.setState({stuArr:stus});
            let newStuarr = stus.filter(item => item.name===searchContent)
            this.setState({stuArr:newStuarr});
        }
        if(type === 'age'){
            this.setState({stuArr:stus});
            let newStuarr = stus.filter(item => item.age===searchContent)
            this.setState({stuArr:newStuarr});
        }
        if(type === 'sex'){
            this.setState({stuArr:stus});
            let newStuarr = stus.filter(item => item.sex===searchContent)
            this.setState({stuArr:newStuarr});
        }
    }
    deleteStu = (name) => {
        let {stus} = this.state;
        let newStuarr = stus.filter(item => item.name!==name)
        this.setState({stuArr:newStuarr,stus:newStuarr});
    }
    state = {
        stuArr: [
            { name: '张三', age: '18', sex: 'male' },
            { name: '李四', age: '20', sex: 'female' },
            { name: '王五', age: '22', sex: 'female' }
        ],
        stus: [
            { name: '张三', age: '18', sex: 'male' },
            { name: '李四', age: '20', sex: 'female' },
            { name: '王五', age: '22', sex: 'female' }
        ]
    }
    render() {
        let { stuArr } = this.state;
        let tableStyle = {width:'500px',textAlign:'center'}
        let toolStyle = {width:'50px',height:'50px',border:'1px solid red',fontSize:'12px'}
        return (
            <div style={{width:'500px',margin:'auto'}}>
                <Addstu addStu={this.addStu}/>
                <Updatestu updateStu={this.updateStu} stuInfo={this.stuInfo?this.stuInfo:''}/>
                <Searchstu searchStu={this.searchStu}/>
                <Showstu stuArr={stuArr} tableStyle={tableStyle} toolStyle={toolStyle} deleteStu={this.deleteStu} updateInfo={this.updateInfo}/>
            </div>
        )
    }

}
